/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.base.web.context;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.base.domain.vo.UserBaseVO;
import com.iwindplus.base.util.CryptoUtil;
import com.iwindplus.base.util.JacksonUtil;
import com.iwindplus.base.web.domain.property.FilterProperty;
import com.iwindplus.base.web.domain.property.FilterProperty.FilterCryptoConfig;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.TraceContext;
import io.micrometer.tracing.Tracer;
import jakarta.annotation.Resource;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;

/**
 * 上下文信息传递管理器.
 *
 * @author zengdegui
 * @since 2025/02/15 21:45
 */
@Slf4j
public class ContextTransManager {

    @Resource
    private FilterProperty filterProperty;

    @Resource
    private Tracer tracer;

    /**
     * 解析用户信息.
     *
     * @param userInfoStr 请求头用户信息字符串
     * @return UserBaseVO
     */
    public UserBaseVO getUserInfo(String userInfoStr) {
        final FilterCryptoConfig crypto = this.filterProperty.getCrypto();
        final String data = CryptoUtil.decrypt(userInfoStr, crypto);
        return JacksonUtil.parseObject(data, UserBaseVO.class);
    }

    /**
     * 获取traceId.
     *
     * @return String
     */
    public String traceId() {
        return Optional.ofNullable(tracer.currentSpan())
            .map(Span::context)
            .map(TraceContext::traceId)
            .filter(CharSequenceUtil::isNotBlank)
            .orElse(UUID.fastUUID().toString(true));
    }
}
